'
描述：
依赖：
返回：
'
gee_qic = function(
  data,                # 数据框
  varsx,               # 自变量（暂时只支持变量名形式，后续会支持 index 形式） 
  varsy,               # 因变量（暂时只支持变量名形式，后续会支持 index 形式）
  varsc = NULL,        # 协变量（暂时只支持变量名形式，后续会支持 index 形式）
  file = "output.xlsx" # 输出文件名
) {
  #wb = createWorkbook()
  cors = c("independence", "exchangeable", "ar1", "unstructured")
  out = NULL
  for (j in 1:length(varsy)) {
    extract_cy_data = data[complete.cases(data[, c(varsy[j], varsc)]), ]                 # 去除因变量、协变量中包含 NA 的行
    for (cor in cors) {
      # 内循环控制自变量的个数
      for (i in 1:length(varsx)) {
        extract_cxy_data = extract_cy_data[complete.cases(extract_cy_data[, varsx[i]]), ]   # 去掉自变量中包含 NA 的行
        y = varsy[j]                                             # 拼接因变量
        x = paste(c(varsx[i], varsc), collapse = " + ")          # 拼接自变量和协变量
        fit = geeglm(formula = as.formula(paste(y, "~", x)),     # 使用 as.formula() 生成公式
                     data = extract_cxy_data,
                     id = id, family = "binomial",
                     corstr = cor, scale.fix = FALSE)
        out1 = as.data.frame(t(QIC(fit)))
        ###### 添加一些变量
        out1$corstr = cor
        out1$y = y
        out1$x = x
        ######
        # 追加结果：内循环第一次执行时 out 为空，会直接赋值为 out1；以后都是追加行
        out = if (is.null(out)) out1 else rbind(out, out1)
      }
    }
    # 输出为单个表格
    #addWorksheet(wb, sheet = varsy[j])
    #writeDataTable(wb, sheet = varsy[j], x = out[, c(-1)])
    #print(paste("Add sheet:", varsy[j], "success."))
  }
  write.xlsx(out[, c(7:9, 1:6)], file, overwrite = T)
  #saveWorkbook(wb, file, overwrite = T)
}

data_test = read.xlsx("./data917.xlsx", 3)
data_anal = data_test[, c(1, 9:13, 14:25, 27, 29:33)]
varsx = colnames(data_test)[c(14:25, 27)]
varsy = colnames(data_test)[c(9:13)]
varsc = colnames(data_test)[c(29:33)]

# 转换变量类型：因变量为数值、自变量为因子
data_anal[varsy] = lapply(data_anal[varsy], as.numeric)
data_anal[varsx] = lapply(data_anal[varsx], as.factor)
gee_qic(data_anal, varsx = varsx, varsy = varsy, varsc = varsc[-5], file = "output1234_QIC.xlsx")
gee_qic(data_anal, varsx = varsx, varsy = varsy, varsc = varsc[-2], file = "output1345_QIC.xlsx")